let toUserName = getUrlString('toUserName');
let markId = getUrlString('markid');
let userId = toUserName.substring(7);
let page = 0;
let count = 10;
let nextPage = true;

//获取对话信息第一页
getnative('dancool://message_getMessagesFromNewest='+toUserName+'|||'+page+'|||'+count+'');

//监听滚动高度加载下一页
$('#chatList').scroll(function(){
    var top = $('#chatList').scrollTop();//滚动条距离顶部的高度
    // console.log(top);
    if(top < 100 && nextPage) {
        console.log(page);
        if (page < 101){
            getnative('dancool://message_getMessagesFromNewest='+toUserName+'|||'+page+'|||'+count+'');
            nextPage = false;
        }
    }
});

// 设置定时器（循环去执行）
var timeId = setInterval(function () {
    getnative('dancool://message_getMessagesFromNewest='+toUserName+'|||0|||9');
}, 3000);

//关闭当前页
$('#goBack').click(function () {
    window.clearInterval(timeId);
    getnative('dancool://message_exitConversation=1');
    nativeCommand("dancool://activity=fin");
});

//去往消息设置
$('.ltsz').click(function () {
    window.location.href = 'dancool://web=https://api.odancool.com/weixinapp/view/messages/chatSet.html?toUserName='+toUserName
});



function getnative(actionurl) {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    if (isiOS) {
        window.webkit.messageHandlers.getnative.postMessage(actionurl);
    }else {
        ikags.getnative(actionurl)
    }
}

//检查是否在黑名单
let isblock;
function isBlack (){
    getData('post','/niu/apiv3/weibo_blackuser.php?method=itemcheck',{'markid':markId,'blockuserid':userId},function (data) {
        console.log(data);
        isblock = data.isblock;
    })
}

isBlack();

//发送单聊消息
let content ;
$('#messageBtn').click(function () {

    content = removeHTMLTag($('#messageInput').html());
    if (isblock === '1'){
        laymsg('双方处于黑名单状态')
    } else{

        if(content === ''){
            laymsg('发送内容不能为空');
            return
        }
        //发送单聊消息
        getnative('dancool://message_createSingleTextMessage='+toUserName+'|||'+content+'');
    }

});



//发送单聊图片
$('#sendImg').click(function () {
    if (isblock === '1'){
        laymsg('双方处于黑名单状态')
    } else {
        getnative('dancool://message_createSingleImageMessage=' + toUserName + '');
    }
});

//拍摄单聊图片
$('#shootImg').click(function () {
    if (isblock === '1'){
        laymsg('双方处于黑名单状态')
    } else {
        getnative('dancool://message_createSingleImageMessagePhoto=' + toUserName + '');
    }
});

function jsnativeresult(tag1,tag2,tag3) {

    let u;
    //获取实时消息
    if (tag1 === 'dancool://message_getMessagesFromNewest='+toUserName+'|||0|||9') {
        let text = tag3.replace(/<[^<>]+>/g,"");
        let jsonTag3 = eval('(' + text + ')');
        // console.log(jsonTag3);
        let createTimeInMillis;

        //判断是否是第一次进来
        let first = $('#chatList').html();

        if (first === ''){
            createTimeInMillis = 1586313285906
        } else {
            createTimeInMillis = $('#chatList .createTimeInMillis:last').val();
        }

        var append = '';
        //数组长度
        var len = jsonTag3.length;
        //json倒转
        var newArray = $.map(jsonTag3, function (v, i) {// map方法匿名函数传的值v是值、i是索引。
            return jsonTag3[len - 1 - i];
        });

        $(newArray).each(function () {
            if (this.createTimeInMillis > createTimeInMillis) {

                if (this.from_id === toUserName) {

                    if (this.msg_type === 'text') {
                        append += '<li class="time">' + getTsFormatDate(this.createTimeInMillis) + '</li>' +
                            '<input type="hidden" class="createTimeInMillis" value="' + this.createTimeInMillis + '"> ' +
                            '      <li class="noMeLi chatListCommon">' +
                            '          <div class="pic">' +
                            '                       <input type="hidden" value="' + this.from_id + '">' +
                            '               <img src="' + getHeaderPic(markId, this.from_id) + '" alt="">' +
                            '          </div>' +
                            '          <div class="chatContent">' +
                            '               <img style="float: left;margin-left: -0.8rem;" src="../../res/img/messages/bsj.png" alt="">' +
                            '               <span>' + this.content.text + '</span></div>' +
                            '      </li>'
                    } else if (this.msg_type === 'image') {

                        let imgUrl = getResource(this.content.media_id);
                        if (imgUrl !== undefined + '-centercrop') {
                            append += '<li class="time">' + getTsFormatDate(this.createTimeInMillis) + '</li>' +
                                '<input type="hidden" class="createTimeInMillis" value="' + this.createTimeInMillis + '"> ' +
                                '<li class="noMeImgLi chatListCommon">' +
                                '                    <div class="pic">' +
                                '                       <input type="hidden" value="' + this.from_id + '">' +
                                '               <img src="' + getHeaderPic(markId, this.from_id) + '" alt="">' +
                                '                    </div>' +
                                '                    <div class="chatContent">' +
                                '                        <img style="margin-left: -0.8rem;vertical-align: top" src="../../res/img/messages/bsj.png" alt="">' +
                                '                        <img class="imgContent" src="' + getResource(this.content.media_id) + '" alt="">' +
                                '                    </div>' +
                                '                </li>';
                        }

                    } else if (this.msg_type === 'file') {
                        let size = ((this.content.fsize) / 1024).toFixed(1);
                        append += '<li class="time">' + getTsFormatDate(this.createTimeInMillis) + '</li>' +
                            '<input type="hidden" class="createTimeInMillis" value="' + this.createTimeInMillis + '"> ' +
                            '<li class="noMeFileLi chatListCommon">' +
                            '                    <div class="pic">' +
                            '                       <input type="hidden" value="' + this.from_id + '">' +
                            '               <img src="' + getHeaderPic(markId, this.from_id) + '" alt="">' +
                            '                    </div>' +
                            '                    <a href="" class="chatContent">' +
                            '                        <img style="margin-left: -0.8rem;vertical-align: top" src="../../res/img/messages/bsj.png" alt="">' +
                            '                        <p class="fileName">' + this.content.fname + '</p>' +
                            '                        <p class="size">' + size + 'MB</p>' +
                            '                    </a>' +
                            '                </li>';
                    }
                } else {

                    if (this.msg_type === 'text') {
                        append += '<li class="time">' + getTsFormatDate(this.createTimeInMillis) + '</li>' +
                            '<input type="hidden" class="createTimeInMillis" value="' + this.createTimeInMillis + '"> ' +
                            '      <li class="meLi chatListCommon">' +
                            '          <div class="pic">' +
                            '               <input type="hidden" value="' + this.from_id + '">' +
                            '               <img src="' + getHeaderPic(markId, this.from_id) + '" alt="">' +
                            '          </div>' +
                            '          <div class="chatContent">' +
                            '               <img style="float: right;margin-right: -0.8rem;" src="../../res/img/messages/hsj.png" alt="">' +
                            '               <span>' + this.content.text + '</span></div>' +
                            '      </li>'
                    } else if (this.msg_type === 'image') {
                        let imgUrl = getResource(this.content.media_id);
                        if (imgUrl !== undefined + '-centercrop') {
                            append += '<li class="time">' + getTsFormatDate(this.createTimeInMillis) + '</li>' +
                                '<input type="hidden" class="createTimeInMillis" value="' + this.createTimeInMillis + '"> ' +
                                '<li class="meImgLi chatListCommon">' +
                                '                    <div class="pic">' +
                                '                       <input type="hidden" value="' + this.from_id + '">' +
                                '                       <img src="' + getHeaderPic(markId, this.from_id) + '" alt="">' +
                                '                    </div>' +
                                '                    <div class="chatContent">' +
                                '                        <img style="float: right;margin-right: -0.8rem;vertical-align: top" src="../../res/img/messages/hsj.png" alt="">' +
                                '                        <img class="imgContent" src="' + imgUrl + '" alt="">' +
                                '                    </div>' +
                                '                </li>';
                        }

                    } else if (this.msg_type === 'file') {
                        let size = ((this.content.msg_body.fsize) / 1024).toFixed(1);
                        append += '<li class="time">' + getTsFormatDate(this.createTimeInMillis) + '</li>' +
                            '<input type="hidden" class="createTimeInMillis" value="' + this.createTimeInMillis + '"> ' +
                            '<li class="meFileLi chatListCommon">' +
                            '                    <div class="pic">' +
                            '                       <input type="hidden" value="' + this.from_id + '">' +
                            '                       <img src="' + getHeaderPic(markId, this.from_id) + '" alt="">' +
                            '                    </div>' +
                            '                    <a href="" class="chatContent">' +
                            '                        <img style="float: right;margin-right: -0.8rem;vertical-align: top" src="../../res/img/messages/hsj.png" alt="">' +
                            '                        <p class="fileName">' + this.content.fname + '</p>' +
                            '                        <p class="size">' + size + 'MB</p>' +
                            '                    </a>' +
                            '                </li>';
                    }
                }
            }
        });
        if (append !== '') {
            $('#chatList').append(append);
            //图片预览
            $('#chatList .noMeImgLi .chatContent .imgContent,#chatList .meImgLi .chatContent .imgContent').click(function () {
                let previewPic = $(this).attr('src');
                let previewPicStr = previewPic.replace('-centercrop', '');
                window.location.href = 'dancool://web=http://api.odancool.com/weixinapp/view/preview/previewPic.html?previewPic=' + previewPicStr;
            });
            //去往个人主页
            $('#chatList .pic').click(function () {
                let id = $(this).find('input').val();
                let userId = id.substring(7);
                window.location.href = 'dancool://member=' + userId;
            });

            //复制文本
            $('#chatList .noMeLi .chatContent span,#chatList .meLi .chatContent span').click(function () {
                let copydata = $(this).html();
                window.location.href="dancool://copydata="+copydata;
            })
            //聊天框默认最底部
            $(document).ready(function () {
                $(".chatList").scrollTop($(".chatList")[0].scrollHeight);
            });
        }
    }


    //获取离线消息
    if(tag1 === 'dancool://message_getMessagesFromNewest='+toUserName+'|||'+page+'|||'+count+''){
        let text = tag3.replace(/<[^<>]+>/g,"");
        let jsonTag3 = eval('(' + text + ')');
        console.log(jsonTag3);
        let createTimeInMillis = $('#chatList .createTimeInMillis:first').val();//获取时间
        //数组长度
        let len = jsonTag3.length;
        //json倒转
        let newArray = $.map(jsonTag3, function (v, i) {
            return jsonTag3[len - 1 - i];
        });
        let append = '';
        // createTimeInMillis > this.createTimeInMillis
        $(newArray).each(function () {

            if (page === 0 || createTimeInMillis > this.createTimeInMillis) {
                $('.title').html(jsonTag3[0].targetInfo.nickname);
                if(this.from_id === toUserName){
                    if(this.msg_type === 'text'){
                        append += '<li class="time">'+getTsFormatDate(this.createTimeInMillis)+'</li>' +
                            '<input type="hidden" class="createTimeInMillis" value="'+this.createTimeInMillis+'"> '+
                            '      <li class="noMeLi chatListCommon">' +
                            '          <div class="pic">' +
                            '                       <input type="hidden" value="'+this.from_id+'">'+
                            '               <img src="'+getHeaderPic(markId,this.from_id)+'" alt="">' +
                            '          </div>' +
                            '          <div class="chatContent">' +
                            '               <img style="float: left;margin-left: -0.8rem;" src="../../res/img/messages/bsj.png" alt="">' +
                            '               <span>'+this.content.text+'</span></div>' +
                            '      </li>'
                    }
                    else if(this.msg_type === 'image'){
                        append += '<li class="time">'+getTsFormatDate(this.createTimeInMillis)+'</li>' +
                            '<input type="hidden" class="createTimeInMillis" value="'+this.createTimeInMillis+'"> '+
                            '<li class="noMeImgLi chatListCommon">' +
                            '                    <div class="pic">' +
                            '                       <input type="hidden" value="'+this.from_id+'">'+
                            '               <img src="'+getHeaderPic(markId,this.from_id)+'" alt="">' +
                            '                    </div>' +
                            '                    <div class="chatContent">' +
                            '                        <img style="margin-left: -0.8rem;vertical-align: top" src="../../res/img/messages/bsj.png" alt="">' +
                            '                        <img class="imgContent" src="'+getResource(this.content.media_id)+'" alt="">' +
                            '                    </div>' +
                            '                </li>';
                    }else if(this.msg_type === 'file'){
                        let size = ((this.content.fsize)/1024).toFixed(1);
                        append += '<li class="time">'+getTsFormatDate(this.createTimeInMillis)+'</li>' +
                            '<input type="hidden" class="createTimeInMillis" value="'+this.createTimeInMillis+'"> '+
                            '<li class="noMeFileLi chatListCommon">' +
                            '                    <div class="pic">' +
                            '                       <input type="hidden" value="'+this.from_id+'">'+
                            '               <img src="'+getHeaderPic(markId,this.from_id)+'" alt="">' +
                            '                    </div>' +
                            '                    <a href="" class="chatContent">' +
                            '                        <img style="margin-left: -0.8rem;vertical-align: top" src="../../res/img/messages/bsj.png" alt="">' +
                            '                        <p class="fileName">'+this.content.fname+'</p>' +
                            '                        <p class="size">'+size+'MB</p>' +
                            '                    </a>' +
                            '                </li>';
                    }
                }else {
                    if(this.msg_type === 'text'){
                        append += '<li class="time">'+getTsFormatDate(this.createTimeInMillis)+'</li>' +
                            '<input type="hidden" class="createTimeInMillis" value="'+this.createTimeInMillis+'"> '+
                            '      <li class="meLi chatListCommon">' +
                            '          <div class="pic">' +
                            '                       <input type="hidden" value="'+this.from_id+'">'+
                            '               <img src="'+getHeaderPic(markId,this.from_id)+'" alt="">' +
                            '          </div>' +
                            '          <div class="chatContent">' +
                            '               <img style="float: right;margin-right: -0.8rem;" src="../../res/img/messages/hsj.png" alt="">' +
                            '               <span>'+this.content.text+'</span></div>' +
                            '      </li>'
                    }
                    else if(this.msg_type === 'image'){
                        append += '<li class="time">'+getTsFormatDate(this.createTimeInMillis)+'</li>' +
                            '<input type="hidden" class="createTimeInMillis" value="'+this.createTimeInMillis+'"> '+
                            '<li class="meImgLi chatListCommon">' +
                            '                    <div class="pic">' +
                            '                       <input type="hidden" value="'+this.from_id+'">'+
                            '                       <img src="'+getHeaderPic(markId,this.from_id)+'" alt="">' +
                            '                    </div>' +
                            '                    <div class="chatContent">' +
                            '                        <img style="float: right;margin-right: -0.8rem;vertical-align: top" src="../../res/img/messages/hsj.png" alt="">'+
                            '                        <img class="imgContent" src="'+getResource(this.content.media_id)+'" alt="">' +
                            '                    </div>' +
                            '                </li>';
                    }else if(this.msg_type === 'file'){
                        let size = ((this.content.msg_body.fsize)/1024).toFixed(1);
                        append += '<li class="time">'+getTsFormatDate(this.createTimeInMillis)+'</li>' +
                            '<input type="hidden" class="createTimeInMillis" value="'+this.createTimeInMillis+'"> '+
                            '<li class="meFileLi chatListCommon">' +
                            '                    <div class="pic">' +
                            '                       <input type="hidden" value="'+this.from_id+'">'+
                            '                       <img src="'+getHeaderPic(markId,this.from_id)+'" alt="">' +
                            '                    </div>' +
                            '                    <a href="" class="chatContent">' +
                            '                        <img style="float: right;margin-right: -0.8rem;vertical-align: top" src="../../res/img/messages/hsj.png" alt="">'+
                            '                        <p class="fileName">'+this.content.fname+'</p>' +
                            '                        <p class="size">'+size+'MB</p>' +
                            '                    </a>' +
                            '                </li>';
                    }
                }
            }
        });

        if (page === 0) {
            $('#chatList').empty().append(append);
            //聊天框默认最底部
            $(".chatList").scrollTop($(".chatList")[0].scrollHeight);
        }else {
            $('#chatList').prepend(append);
        }
        page +=10;//增加10条数据
        nextPage = true;
        //图片预览
        $('#chatList .noMeImgLi .chatContent .imgContent,#chatList .meImgLi .chatContent .imgContent').click(function () {
            let previewPic = $(this).attr('src');
            let previewPicStr = previewPic.replace('-centercrop','');
            window.location.href = 'dancool://web=http://api.odancool.com/weixinapp/view/preview/previewPic.html?previewPic='+previewPicStr;
        });
        //去往个人主页
        $('#chatList .pic').click(function () {
            let id = $(this).find('input').val();
            let userId = id.substring(7);
            window.location.href = 'dancool://member='+userId;
        });
        //复制文本
        $('#chatList .noMeLi .chatContent span,#chatList .meLi .chatContent span').click(function () {
            let copydata = $(this).html();
            window.location.href="dancool://copydata="+copydata;
        })
    }
    u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    //发送单聊消息
    if (tag1 === 'dancool://message_createSingleTextMessage='+toUserName+'|||'+content+'') {
        let jsonTag3 = $.parseJSON(tag3);
        console.log(jsonTag3);

        $('#messageInput').html('');
        // if (isiOS){
        //     $('#messageInput').html('');
        // }else {
        //     $('#messageInput').html('');
        //     let append = '<li class="time">'+getTsFormatDate(jsonTag3.createTimeInMillis)+'</li>' +
        //         '<input type="hidden" class="createTimeInMillis" value="'+jsonTag3.createTimeInMillis+'"> '+
        //         '      <li class="meLi chatListCommon">' +
        //         '          <div class="pic">' +
        //         '                       <input type="hidden" value="'+this.from_id+'">'+
        //         '               <img src="'+getHeaderPic(markId,jsonTag3.from_id)+'" alt="">' +
        //         '          </div>' +
        //         '          <div class="chatContent">' +
        //         '               <img style="float: right;margin-right: -0.8rem;" src="../../res/img/messages/hsj.png" alt="">' +
        //         '               <span>'+jsonTag3.content.text+'</span></div>' +
        //         '      </li>';
        //     $('#chatList').append(append);
        //     $(".chatList").scrollTop($(".chatList")[0].scrollHeight);
        // }
    }

    //发送单聊图片
    if (tag1 === 'dancool://message_createSingleImageMessage='+toUserName+''){
        let jsonTag3 = $.parseJSON(tag3);
        console.log(jsonTag3);
        // if (isiOS){
        //     let append = '<li class="time">'+getTsFormatDate(jsonTag3.createTimeInMillis)+'</li>' +
        //         '<input type="hidden" class="createTimeInMillis" value="'+jsonTag3.createTimeInMillis+'"> '+
        //         '<li class="meImgLi chatListCommon">' +
        //         '                    <div class="pic">' +
        //         '                       <input type="hidden" value="'+jsonTag3.from_id+'">'+
        //         '                       <img src="'+getHeaderPic(markId,jsonTag3.from_id)+'" alt="">' +
        //         '                    </div>' +
        //         '                    <div class="chatContent">' +
        //         '                        <img style="float: right;margin-right: -0.8rem;vertical-align: top" src="../../res/img/messages/hsj.png" alt="">'+
        //         '                        <img class="imgContent" src="'+getResource(jsonTag3.content.media_id)+'" alt="">' +
        //         '                    </div>' +
        //         '                </li>';
        //     $('#chatList').append(append);
        //     $(".chatList").scrollTop($(".chatList")[0].scrollHeight);
        // }
    }
}

function removeHTMLTag(str) {
    str = str.replace(/<\/?[^>]*>/g,''); //去除HTML tag
    str = str.replace(/[ | ]*\n/g,'\n'); //去除行尾空白
    //str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
    str=str.replace(/&nbsp;/ig,'');//去掉&nbsp;
    return str;
}